import axios from 'axios';
import { ElMessageBox, ElMessage } from 'element-plus';
import storage from './storage';

// 创建一个axios实例
const request = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL || 'https://messln.cn/api', // 获取环境变量配置
    timeout: 10000, // 设置超时时间
});

// request拦截
request.interceptors.request.use(
    (config: any) => {
        const { url } = config;
        if (storage.get('token')) {
            config.headers['Authorization'] = 'Bearer ' + storage.get('token');
        }

        config.headers['Content-Type'] = 'application/json';

        return config;
    },
    (error: any) => {
        console.log(error); // for debug
        return Promise.reject(error);
    }
);

// response interceptor
request.interceptors.response.use(
    (response: any) => {
        const code = response.data.code;
        if (code == 401) {
            storage.remove('token');
            if (location.href.indexOf('login') != -1) {
                location.reload(); // 为了重新实例化vue-router对象 避免bug
            } else {
                ElMessageBox.confirm(
                    '登录状态已过期，您可以继续留在该页面，或者重新登录',
                    '系统提示',
                    {
                        confirmButtonText: '重新登录',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                ).then(() => {
                    location.reload(); // 为了重新实例化vue-router对象 避免bug
                });
            }
        } else if (code == 6401) {
            storage.remove('token');
            ElMessageBox.confirm(
                '登录状态已过期，您可以继续留在该页面，或者重新登录',
                '系统提示',
                {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                location.reload(); // 为了重新实例化vue-router对象 避免bug
            });
            return false;
        } else if (code == 400 || code == 403) {
            ElMessage({
                message: response.data.message,
                type: 'error',
                duration: 5 * 1000,
            });
        } else {
            return response.data;
        }
    },
    (error: any) => {
        console.log('err', error, error.response); // for debug
        if (error.message == 'Network Error') {
            ElMessage({
                message: '服务器连接异常，请检查服务器！',
                type: 'error',
                duration: 5 * 1000,
            });
            return;
        }

        ElMessage({
            message: error.response?.data?.message,
            type: 'error',
            duration: 5 * 1000,
        });

        return Promise.reject(error);
    }
);
// 参数定义
interface data {
    url: string;
    data?: any;
}
function get(data: data) {
    return request({
        url: data.url,
        method: 'get',
        params: data.data,
    });
}
function put(data: data) {
    return request({
        url: data.url,
        method: 'put',
        data: data.data,
    });
}
function post(data: data) {
    return request({
        url: data.url,
        method: 'post',
        data: data.data,
    });
}
function deleteReq(data: data) {
    return request({
        url: data.url,
        method: 'delete',
        data: data.data,
    });
}
function patch(data: data) {
    return request({
        url: data.url,
        method: 'patch',
        data: data.data,
    });
}

export { get, put, post, deleteReq, patch };
